<template>
    <div class="insert-box">
        <div class="insert-title flex-center-col">
            <div style="margin-top: 20px">
                <span class="title-text">标题 : </span>
                <el-input type="text" v-model="obj.title"
                          class="title-input"
                          prefix-icon="el-icon-edit"
                          maxlength="100"
                          @blur="checkTitle"
                          minlength="5"
                ></el-input>


            </div>


            <div style="text-align: right;width: 700px;color: #adacac">

                字数 : <span :style="{color:obj.title.length<5?'tomato':'gray'}">
                            {{obj.title.length}}
                     </span>/100
            </div>
        </div>


<!--        编辑模块-->

        <div class="insert-content-box" @blur="checkContent">
            <div class="insert-content">
                <MyEditor  @html="setHtml" @text="setText"   >

                </MyEditor>
            </div>
        </div>



<!--        配置模块-->
        <div class="insert-config-box flex-center">
            <div class="config">
                <div class="config-item">
                    置顶 :
<!--                    置顶-->
                    <el-switch
                            v-model="obj.config.top"
                            active-color="#42b983"
                            inactive-color="#ff4949"
                            active-value=1
                            inactive-value=0
                            active-text="置顶"
                            active-icon-class="el-icon-success"
                            :width="60"
                    >
                    </el-switch>
                </div>

<!--                分类选择-->
                <div class="config-item">
                    选择分类 :
                    <el-radio-group v-model="obj.config.tab"
                                    fill="#42b983"
                    >
                        <el-radio-button v-for="i in obj.tabList"
                                         :label="i.tId"
                                         class="radio-button"
                        >{{i.tName}}</el-radio-button>
                    </el-radio-group>
                </div>
                选择图片
                <div>
                    <el-upload
                            ref="elUpload"
                            :accept="this.upload.accept"
                            :action="this.upload.uploadUrl"
                            list-type="picture-card"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove"
                            :auto-upload="false"
                            :limit="2"
                            name="file"
                            :headers="{
                                token:obj.token
                            }"
                            :data="{
                                 aId:obj.id,
                                tId:obj.config.tab,
                                aPublish:obj.config.publish,
                                aTop:obj.config.top,
                                aTitle:obj.title,
                                aContent:obj.content.html
                              }"
                            :on-success="submitSuccess"
                            :on-error="submitError"
                            :on-change="imageChange"
                            with-credentials
                    >
                        <i class="el-icon-plus" ></i>
                    </el-upload>
                    <el-dialog :model-value="upload.dialogVisible" :visible.sync="upload.dialogVisible">
                        <img width="100%" :src="upload.dialogImageUrl" alt="">
                    </el-dialog>
                </div>


            </div>

        </div>

        <div class="bottom-submit-box flex-center">
                <div class="sub-text">
                    文字
                </div>
                <el-button   @click="cancel">取消</el-button>
                <el-button class="not-publish-btn" @click="NotPublishSub">草稿</el-button>
                <el-button class="sub-btn" @click="subForm">提交</el-button>
        </div>

    </div>
</template>

<script>
    import MyEditor from "@/components/article/MyEditor";
    import {reactive, ref} from "@vue/reactivity";
    import axios from 'axios'
    import {onMounted} from "@vue/runtime-core";
    import {useRouter} from "vue-router";
    import Upload from "@/components/other/Upload";
    import {ElMessage} from "element-plus";
    import {errorMessage, goTop, rejectMessage} from "@/assets/js/utils";
    export default {
        name: "InsertArticle",
        components:{Upload, MyEditor},
        setup(){
            const router=useRouter()
            let obj=reactive({
                token:localStorage.getItem('token'),
                id:0,
                title:"",
                content:{
                    html:"",
                    text:""
                },
                tabList:[],
                config:{
                    tab:0,
                    top:0,
                    publish:1,
                    image:{},
                    hasImage:false
                }
            })
            let elUpload=ref()

            let upload=reactive({
                uploadUrl:"/api/ylb/article/insert/hasImage",
                accept:".jpg,.jpeg,.png,.gif",
                dialogImageUrl:"",
                dialogVisible:false
            })




            function getTabList(){
                return axios.get("/api/tabs").then(resp=>resp.data)
            }

            function setText(text){
               obj.content.text=text
            }
            function setHtml(html){
                obj.content.html=html
            }

            function cancel(){
                router.go(-1)
            }

            let checkTitle=()=>{
                const title=obj.title.length
                if(title===0){
                    alert('标题为空')
                    return false
                }
                if(title>100){
                    alert('标题小于100')
                    return false
                }
                return true
            }
            let checkContent=()=>{
                const text=obj.content.text.length

                if(text===0){
                    alert('文章不为空')
                    return false
                }

                if(text>5000){
                    alert('文章太大')
                    return false
                }
                return true
            }


            let checkForm=()=>{

                if(!checkTitle()){
                    return false
                }
                if(!checkContent()){
                    return false
                }

                if(obj.config.tab===0){

                    alert('任选一个标签')
                    return false
                }

                return true
            }


            let subForm=()=>{
                if(checkForm()){
                    // 如果有图片
                    if(obj.config.hasImage){

                        elUpload.value.submit();
                    }

                    // 如何没有图片
                    else{

                        submit()
                    }

                }else{
                    console.log('checkFail')
                }
            }
            let submit=()=>{

                let router=useRouter()
                const data=getFormData()

                axios.post("/api/ylb/article/insert", {
                        aTop:obj.config.top,
                        aPublish:obj.config.publish,
                        tId:obj.config.tab,
                        aTitle:obj.title,
                        aContent:obj.content.html,
                },{
                    headers:{
                        token:obj.token
                    }
                }).then(resp=>{
                    if(resp.data.code===200){
                        alert("添加成功")
                        // 跳转到展示页面
                        router.push({
                            path:"/article",
                            query:{
                                aId:resp.data.data.aId
                            }
                        })

                    }else{
                        if(rejectMessage(resp)){

                        }else{
                            errorMessage("添加失败:"+resp.data.msg)
                        }

                    }
                }).then(error=>{

                })
            }

            function getFormData(){
                let data=new FormData

                data.append("aTop",obj.config.top)
                data.append("aPublish",obj.config.publish)
                data.append("atId",obj.config.tab)
                data.append("aTitle",obj.title)
                data.append("aContent",obj.content.html)
                data.append("aId",obj.id)
                data.append('file',obj.config.image)
                return data
            }


            let NotPublishSub=()=>{
                obj.config.publish=0
                subForm()
            }



            // ------------------upload--------------------
            function submitSuccess(res, file,fileList){

                console.log(res)
                if(res.code===200){
                    // 提示
                   ElMessage.success({
                       message: '添加成功',
                       type: 'success',
                       showClose:true,
                       center: true,
                       // dangerouslyUseHTMLString: true,
                   })
                    router.push("/bc/artController")
                }else{
                    alert('失败')
                }

            }


            function submitError(err, file, fileList){
                console.log(err)

            }

            function handlePictureCardPreview(file) {
                upload.dialogImageUrl = file.url;
                upload.dialogVisible = true;
            }
            function imageChange(file,fileList){

                if(fileList.length>1){
                    fileList.splice(0,1);
                }
                obj.config.hasImage=true

            }
            function handleRemove() {
                obj.config.hasImage=false
            }


            onMounted(async() =>{
                const data=await  getTabList()
                if(data.code===200){
                    obj.tabList=data.data;
                }
                goTop()
            })
            return{
                obj,
                setHtml,
                setText,
                subForm,
                cancel,
                NotPublishSub,
                upload,
                handlePictureCardPreview,
                handleRemove,
                submitSuccess,
                submitError,
                imageChange,
                elUpload,
                checkTitle,
                checkContent


            }
        }
    }
</script>

<style scoped lang="less">
    @Insert-width:1000px;
    .insert-box{

        width: 100%;
        background-color: var(--theme-color);
        display: flex;
        flex-direction: column;
        align-items: center;

        .insert-title{
            width: @Insert-width;
            height: 150px;
            margin-top: 80px;
            margin-bottom: 50px;
            font-size: 20px;
            border-radius: 5px;
            background-color: white;
            .title-text{
                color: #42b983;
                margin-right: 10px;

            }
            .title-input{
                width: @Insert-width*.8;
                font-size: 20px;
                height: 50px;
            }
        }
        .insert-content-box{
            width: @Insert-width;

            .insert-content{
                border-radius: 5px;

            }

        }
        .insert-config-box{
            width: @Insert-width;
            min-height: 600px;
            background-color: rgba(255, 255, 255, 0.97);
            margin-top: 100px;
            .config{
                width: 80%;
                height: 80%;
                margin-top: 40px;
                text-align: left;

                .config-item{
                    width: 100%;
                    font-size: 18px;
                    margin:10px 0 20px 0;
                    .radio-button{
                        background-color: var(--theme-color);
                        color: white;
                        border-radius: 5px;
                        margin:5px 10px 5px 0;
                    }


                }

            }
        }


        .bottom-submit-box{

            width: 100%;
            height: 80px;
            margin-top: 100px;
            background-color:#BE3850;
            margin-bottom: 100px;


            .sub-text{
                width: 500px;
                color: white;
            }
            .sub-btn{
                width: 100px;
                color: white;
                background-color: #42b983;
                border: 0;
            }
            .sub-btn:hover{
                background-color: rgba(72, 203, 143, 0.97);
            }
            .not-publish-btn{
                width: 100px;
                color: white;
                background-color: orangered;
                border: 0;
            }
            .not-publish-btn:hover{

                background-color: rgba(255, 69, 0, 0.95);

            }


        }

    }



</style>